<?php

namespace Activity;

use C\L\WebController;

class InviteController extends WebController
{
    public function indexAction()
    {
        $uid = $this->uid;

        $inviteTypes = [
        'register_superior_money',
        'group_buying_confirm_order_superior_reward',
        'group_buying_confirm_user_order_superior_reward',
        ];

        $sum = $this->s_funds->getSum(
            'money',
            [
            'uid'   => $uid,
            'stype' => $inviteTypes,
            ],
            [
            'uid'   => '=',
            'stype' => 'in'
            ],
        );

        $path = '/api/api/qrcode?uid=' . $uid . '&x=' . substr(md5(rand(1, 9999)), 0, 9);
        $data = [
        'invite_user_count'  => $this->s_user->getCount(['t_uid' => $uid]),
        'invite_rewards_sum' => $sum,
        'invite_image_url'   => $this->convertAssetsUrl($path),
        ];

        $this->success($data);
    }

    public function usersAction()
    {
        $currentPage = $this->request->getQuery('page', 'int', 1);
        $perPage     = $this->request->getQuery('per_page', 'int', 20);

        $builder = $this
        ->modelsManager
        ->createBuilder()
        ->columns(['uid', 'mobile', 'addtime'])
        ->from('C\M\User')
        ->andWhere('t_uid = :inviter_id:', ['inviter_id' => $this->uid])
        ->orderBy('uid DESC');

        $result = $this->paginationByBuilder($builder, $currentPage, $perPage);

        return $this->success($result);
    }

    public function rewardsAction()
    {
        $currentPage = $this->request->getQuery('page', 'int', 1);
        $perPage     = $this->request->getQuery('per_page', 'int', 20);
        $inviteTypes = [
        'register_superior_money',
        'group_buying_confirm_order_superior_reward',
        'group_buying_confirm_user_order_superior_reward',
        ];

        $builder = $this
        ->modelsManager
        ->createBuilder()
        ->columns(['id', 'title', 'money', 'addtime'])
        ->from('C\M\UserFunds')
        ->andWhere('uid = :user_id:', ['user_id' => $this->uid])
        ->inWhere('stype', $inviteTypes)
        ->orderBy('id DESC');

        $result = $this->paginationByBuilder($builder, $currentPage, $perPage);

        return $this->success($result);
    }
}
